package com.zjm.filter.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ZJM
 * @date 2024/4/26 21:53
 * Filter过滤器
 */
public class AdminFilter implements Filter {

    public AdminFilter() {
        System.out.println("1.Filter构造方法");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("2.Filter的init初始化");
        // 1.获取Filter的名称filter-name内容
        System.out.println("filter-name值：" + filterConfig.getFilterName());
        // 2.获取Filter中配置的init-param初始化参数
        System.out.println("init-param值：" + filterConfig.getInitParameter("username"));
        // 3.获取ServletContext对象
        System.out.println("ServletContext对象:" + filterConfig.getServletContext());
    }

    /**
     * doFilter方法，专门用于拦截请求，过滤响应，可以做权限检查
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("3.doFilter方法");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user == null) {
            request.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
            return;
        } else {
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("4.Filter的destroy()");
    }
}
